;!function(win, xxim) {
    xxim.sendMsg = function(data) {
        stompClient.send(xxim.config.api.msgSendUrl, {}, JSON.stringify({
            'fromUserId' : data.fromUserId,
            'toDestId' : data.toDestId,
            'messageContent' : data.messageContent,
            "sendTime" : new Date().getTime(),
            "readFlag" : 0,
            "messageType" : 1
        }));
    }
    
    // ***** 聊天记录模块开始 ***** //
    xxim.log = {
        // 聊天模版
        html : function(param, type) {
            return '<li class="'
                    + (type === 'me' ? 'layim_chateme' : '')
                    + '">'
                    + '<div class="layim_chatuser">'
                    + function() {
                        if (type === 'me') {
                            return '<span class="layim_chattime">' + param.time
                                    + '</span>'
                                    + '<span class="layim_chatname">'
                                    + param.name + '</span>' + '<img src="'
                                    + param.face + '" >';
                        } else {
                            return '<img src="' + param.face + '" >'
                                    + '<span class="layim_chatname">'
                                    + param.name + '</span>'
                                    + '<span class="layim_chattime">'
                                    + param.time + '</span>';
                        }
                    }() + '</div>' + '<div class="layim_chatsay">'
                    + param.content + '<em class="layim_zero"></em></div>'
                    + '</li>';
        },

        append : function(data) {
            var usrId = data.fromUserId;
            var chatingUserLst = $('div.layim_chatmore ul.layim_chatlist li[data-id= ' + usrId + ' ]');
            msgQueueMap = xxim.log.msgQueueMap

            if (!chatingUserLst || chatingUserLst.length == 0) { // 未打开聊天窗口，消息入队列并提示新消息
                var msgQue = msgQueueMap[usrId]
                if (msgQue) {
                    msgQue.push(data)
                } else {
                    msgQueueMap[usrId] = [ data ]
                }
            } else {
                var keys = xxim.nowchat.type + xxim.nowchat.id;
                var msgType = data.messageType == 1 ? "one" : "group";
                var fromId = data.fromUserId;
                keys = msgType + fromId
                var imarea = xxim.chatbox.find('#layim_area' + keys);
                imarea.append(log.html({
                    time : new Date(parseInt(data.sendTime))
                            .format("yyyy-MM-dd hh:mm:ss"),
                    name : fromId,
                    face : xxim.nowchat.face,
                    content : data.messageContent
                }));
                imarea.scrollTop(imarea[0].scrollHeight);
            }
        },
        /*
         * 未处理的消息队列。 格式： { 用户ID: [消息队列] }
         * 
         */
        msgQueueMap : {},
        _notifyChecker : null,
        // xxim.log
        // 新消息检测与通知
        initNotifyCheck : function() {
            xxim.log._notifyChecker = setInterval(function() {
                if ($.isEmptyObject(xxim.log.msgQueueMap) == false) {
                    $('#xxim_mymsg i').fadeToggle('fast');
                    $('#xxim_mymsg').attr('title', '你有新消息');
                } else {
                    $('#xxim_mymsg').attr('title', '当前没有新消息');
                }
            }, 1000);

            $('#xxim_mymsg').click( function() {
                if ($.isEmptyObject(xxim.log.msgQueueMap) == false) {
                    for (userId in xxim.log.msgQueueMap) {
                        var friItem = $('ul.xxim_list ul.xxim_chatlist li.xxim_childnode[data-id='
                                + userId + ']')
                        var face;
                        if (!friItem || friItem.length == 0) {
                            var usrDat = xxim.user.get(userId);
                            var grpLst = $('ul.xxim_list li.xxim_parentnode[data-id=2] ul.xxim_chatlist'); // 陌生人分类
                            var usrItem = '<li data-id="'
                                    + usrDat.loginId
                                    + '" class="xxim_childnode" type="one"><img src="'
                                    + usrDat.avatar
                                    + '" class="xxim_oneface"><span class="xxim_onename">'
                                    + usrDat.loginId
                                    + '</span></li>';
                            grpLst.append(usrItem);
                            xxim.category.refreshNum();
                            face = usrDat.avatar;
                            friItem = $(usrItem);
                        } else {
                            face = friItem.find('img').attr(
                                    'src');
                        }

                        xxim.popchatbox(friItem);
                        var msgArr = xxim.log.msgQueueMap[userId];
                        for (idx in msgArr) {
                            msg = msgArr[idx]
                            xxim.log.append(msg);
                        }
                        delete xxim.log.msgQueueMap[userId]
                    }
                    $('#xxim_mymsg i').show();
                }
            })
        },
        stopNotifyCheck : function() {
            if (xxim.log._notifyChecker) {
                xxim.log._notifyChecker.cancel();
                xxim.log._notifyChecker = null;
            }
        },
        init : function() {
            xxim.log.initNotifyCheck();
        }
    }
    // ***** 聊天记录模块结束 ***** //
    
    xxim.retriveMessage = function() {
        $.get(xxim.config.api.retrieveMsgUrl, function(dat, ss) {
            console.log("got msg", dat);
            for ( var d in dat.data) {
                xxim.log.append(dat.data[d]);
            }
        })
    }

    xxim.connectWithWebSocket = function() {
        var socket = new SockJS('/shzg_im/swapper');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {
            stompClient.subscribe(xxim.config.api.websocketUrl + xxim.config.user.id, function(chat) {
                var msgInfo = (JSON.parse(chat.body)).data;
                xxim.log.append(msgInfo[0]);
            });

            stompClient.subscribe(xxim.config.api.initChatLogUrl + xxim.config.user.id, function(log) {
                // localStorage.chatlog = log;

                for ( var d in log.data) {
                    xxim.log.append(log.data[d]);
                }
            });
        })
    }

    // ***** 用户模块开始 ***** //
    xxim.user = {
        hasFriend : function(friId) {
            var friArr = $('.xxim_list').eq(0).find(
                    'li.xxim_parentnode[data-id=1] .xxim_chatlist li.xxim_childnode[data-id='
                            + friId + ']')
            var isAdded = (friArr && friArr.length != 0);
            return isAdded;
        },
        search : function(keyWords) {
            $('#xxim_searchmain li').remove();
            $.get('user/search/' + keyWords, {}, function(dat) {
                if (dat.data.length == 0) {
                    xxim.node.searchMian
                            .append('<li>没有搜索结果</li>');
                }
                for (idx in dat.data) {
                    var usrInfoMap = dat.data[idx]
                    var friArr = $('.xxim_list').eq(0).find(
                            'li.xxim_parentnode[data-id=1] .xxim_chatlist li.xxim_childnode[data-id='
                                    + usrInfoMap.loginId + ']')
                    var friAdded = (friArr && friArr.length != 0);
                    var addInfoStr = friAdded ? '已添加' : '添加'
                    var itemStr = '<li data-id="'
                            + usrInfoMap.loginId
                            + '" class="xxim_childnode"><img src="'
                            + usrInfoMap.avatar
                            + '" class="xxim_oneface"><span class="xxim_onename">'
                            + usrInfoMap.nickName
                            + '</span><i>' + addInfoStr
                            + '</i></li>';
                    xxim.node.searchMian.append(itemStr);

                    (function(friId) {
                        $('#xxim_searchmain li i').eq(idx).on('click', function() {
                            if (xxim.user.hasFriend(friId)) {
                                
                            } else {
                                xxim.user.add(friId)
                                xxim.category.refreshNum();
                            }
                        })
                    })(usrInfoMap.loginId);
                }
            })
        },
        // 添加好友
        add : function(destUserId) {
            var catId = $('.xxim_top ul.xxim_list').eq(0).find('li.xxim_parentnode[data-id=1]').data('id')

            $.post('user/friend/add', {"destUserId" : destUserId, "catId" : catId}, function(d) {
                console.log('add user ok', d);
                xxim.getDates(0);
                xxim.node.searchMian.find('li[data-id=' + d.data.destUserId + '] i').text('已添加');
            })
        },
        loginOk : function() {
            $('.loginPage').fadeOut(function() {
                $('#xxim_top').fadeIn();
                $('ul.xxim_bottom li').fadeIn();
            });

            xxim.getDates(0);
            xxim.event();
            xxim.initEvent();

            xxim.connectWithWebSocket();
        },
        logout : function() {
            // 关闭聊天窗口
            stompClient.disconnect(function() {
                var closeBtn = $('div.xubox_main div.xuboxPageHtml i.layim_close')
                if (closeBtn) {
                    closeBtn.click();
                }

                $.get('user/logout/json', function() {
                    $('#xxim_top').fadeOut(function() {
                        $("div.loginForm input[name=password]").val('')
                        $('div.loginPage').fadeIn();
                    });
                    $('ul.xxim_bottom').children().fadeOut();
                })
            })
        },
        removeFriend : function(friId) {
            if (!friId)
                return;
            var chattingFriBox = $('div.layim_chatbox div.layim_chatmore ul.layim_chatlist li[data-id' + friId + ']')
            if (chattingFriBox && chattingFriBox.length != 0) { // 判断聊天窗口是否打开
                chattingFriBox.find('em').click();
            }
            $.post('user/friend/del/' + friId, function() {
                $('ul.xxim_list ul.xxim_chatlist li[data-id=' + friId + ']').remove();
                xxim.chat.toolBar.hide();
                xxim.category.refreshNum();
            })
        },
        get : function(usrId) {
            if (!usrId)
                return;
            var userInfo;
            $.ajax('user/' + usrId, {
                async : false
            }).done(function(d) {
                userInfo = d.data
            });
            return userInfo;
        }
    };
    // ***** 用户模块结束 ***** //
    
    xxim.category = {
        refreshNum : function() {
            $('ul.xxim_list').eq(0).find('li.xxim_parentnode').each(function() {
                var usrNum = $(this).find('ul.xxim_chatlist li.xxim_childnode').length;
                $(this).find('h5 em.xxim_nums').text('（' + usrNum + '）')
            })
        }
    }

    // 初始化登录
    xxim.initLogin = function() {
        $.get('user', function(d) {
            if (d.status == 1) { // 判断是否已经登录
                var userInfo = d.data;
                xxim.config.user = {
                    id : userInfo.loginId,
                    face : userInfo.avatar,
                    nickName : userInfo.nickName,
                    description : userInfo.description
                }
                $("div.loginForm input[name=login_id]").val(userInfo.loginId)
                $("div.loginForm input[name=password]").val('******')

                xxim.user.loginOk();
            }
        })

        $("div.loginForm").keyup(function(e) {
            if (e.keyCode === 13) { // Enter
                $("div.loginForm input[type=button]").click();
            }
        });

        $("div.loginForm input[type=button]").click(
            function() {
                var loginId = $("div.loginForm input[name=login_id]").val().replace(/\s/g, '');
                var password = $("div.loginForm input[name=password]").val().replace(/\s/g, '');

                var errInfo = '';
                if (loginId === '') {
                    errInfo = '登录ID不能为空！'
                } else if (password === '') {
                    errInfo = '密码不能为空！'
                } else {
                    $.ajax({
                        url : 'user/login/json',
                        async : false,
                        data : {
                            "login_id" : loginId,
                            "password" : password
                        },
                        method : 'POST'
                    }).done(function(d) {
                        var userInfo = d.data;
                        xxim.config.user = {
                            id : userInfo.login_id,
                            face : userInfo.avatar,
                            nickName : userInfo.nick_name,
                            description : userInfo.description
                        }
                        xxim.user.loginOk();
                    });
                }
                $("div.loginForm .infoSpan").text(errInfo);
            })
    }

    xxim.user.profile = xxim.user.profile || {}
    xxim.user.profile = {
        init : function() {
            $("div.profileForm input[name=save]").click(function() {
                xxim.user.profile.save();
            })
        },
        save : function() {
            var proDat = {}
            function collect() {
                for (idx in arguments) {
                    name = arguments[idx]
                    proDat[name] = $("div.profileForm [name=" + name + "]").val();
                }
            }

            collect('loginId', 'avatar', 'description', 'nickName', 'password')
            $.post('user/profile', proDat, function() {

            })
        }
    }

    xxim.chat = xxim.chat || {}
    // 删除好友把手
    xxim.chat.toolBar = {
        hide : function() {
            var toolBar = $('.xxim_top .chatToolBar');
            toolBar.fadeOut();
        },
        init : function() {
            var chatLst = $('ul.xxim_list').eq(0);
            var toolBar = $('.xxim_top .chatToolBar');

            chatLst.find('ul.xxim_chatlist li').hover(function(e) {
                toolBar.css('top', $(this).position().top + 10);
                toolBar.fadeIn(function() {
                    $('.chatToolBar').show()
                });
                toolBar._currentItem = $($(this)[0]);
            })

            $('div.xxim_top').mouseleave(function() {
                toolBar.fadeOut();
                toolBar._currentItem = undefined;
            })

            toolBar.click(function() {
                if (toolBar._currentItem) {
                    xxim.user.removeFriend(toolBar._currentItem.data('id'))
                }
            })
        }
    }

    Date.prototype.format = function(fmt) {
        var o = {
            "M+" : this.getMonth() + 1,
            "d+" : this.getDate(),
            "h+" : this.getHours(),
            "m+" : this.getMinutes(),
            "s+" : this.getSeconds(),
            "q+" : Math.floor((this.getMonth() + 3) / 3),
            "S" : this.getMilliseconds()
        }

        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "".substr(4 - RegExp.$1.length)));
            for ( var k in o) {
                if (new RegExp('(' + k + ')').test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
                }
            }
        }
        return fmt
    }
    // 登录成功后初始化函数
    xxim.initEvent = function() {
        xxim.user.profile.init();
        xxim.chat.toolBar.init();
        xxim.log.initNotifyCheck();
    }

    xxim.destroy = function() {
        xxim.log.stopNotifyCheck();
    }

    xxim.init();
    xxim.initLogin();

    var stompClient;

}(window, xxim)